package com.xuan.contest.common.job;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * @author XinZhaoXuan
 * @date 2018/9/7
 */
@Component
public class ExecuteJob {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    final String jobGroup = "CONTEST";

    /**
     * 该方法用来启动所有的定时任务
     *
     * @throws SchedulerException
     */
    public void startJob(Class clazz, String cron) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(clazz.getName(), jobGroup).build();

        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(clazz.getName(), jobGroup).withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);

    }


    public void stopJob(Class clazz) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.deleteJob(JobKey.jobKey(clazz.getName(), jobGroup));
        scheduler.clear();
    }
}
